<?php
/**
 * This file is part of the jdufs project
 *
 * (c) tiglog <xq@tiglog.com>
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace tiglog\datatables;

use Yii;
use Closure;
use yii\base\BaseObject;
use yii\helpers\Html;
use yii\base\Model;
use yii\helpers\Inflector;
use yii\helpers\ArrayHelper;

class DataColumn extends BaseObject
{

    public $dt;

    /**
     * 也即是 attribute or field
     */
    public $attribute;
    public $format = 'text';
    public $label;
    public $value;
    public $sort;
    public $searchable = false;
    public $type;
    public $headerOptions = [];


    public function getLabel()
    {
        if (!$this->label) {

            if($modelClass = $this->dt->getModelClass()) {
                $model = new $modelClass;
            } else {
                $model = null;
            }

            if ($model and $model instanceOf Model) {
                $this->label = $model->getAttributeLabel($this->attribute);
            } else {
                $this->label = Inflector::camel2words($this->attribute);
            }
        }
        return $this->label;
    }

    public function getHeaderOptions()
    {
        return $this->headerOptions;
    }

    public function renderHeaderCell()
    {
        return Html::tag('th', $this->getLabel(), $this->getHeaderOptions());
    }

    public function renderDataCell($model)
    {
        $val = $this->getDataCellValue($model);
        return $this->widget->formatter->format($val, $this->format);
    }

    public function getDataCellValue($model)
    {
        if ($this->value !== null) {
            if (is_string($this->value)) {
                $val = $this->value;
            } else {
                $val = call_user_func($this->value, $model, $this);
            }
            return $val;
        }
        if(!$model) {
            return null;
        }
        return ArrayHelper::getValue($model, $this->attribute);
    }

    public function isSearchAble()
    {
        return $this->attribute && $this->searchable;
    }

    public function search(&$query, $kw)
    {
        if (!$this->isSearchAble()) {
            return $query;
        }
        if ($this->type == 'string') {
            $query->orFilterWhere(['like', $this->attribute, $kw]);
        } else {
            $query->orFilterWhere([$this->attribute=>$kw]);
        }
        return $query;
    }



}



// vim:ft=php:ts=4:sts=4:sw=4:et
